package com.leiyun.lamekit;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.widget.Toast;


/**
 * Created by Kvin on 2017/4/28.
 */
public class PermissionUtils {
    /**
     * check permission
     */
    public static boolean isPermitted(Context context, String permission) {
        if (TextUtils.isEmpty(permission)) {
            throw new RuntimeException("permission cannot be null");
        }
        int status = ContextCompat.checkSelfPermission(context, permission);
        return status == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * check a related group permission
     *
     * @param context
     * @param permission
     * @return
     */
    public static boolean isPermitted(Context context, String[] permission) {
        if (permission == null || permission.length <= 0) {
            throw new RuntimeException("permission cannot be null");
        }
        boolean per = true;
        for (int i = 0; i < permission.length; i++) {
            int status = ContextCompat.checkSelfPermission(context, permission[i]);
            per = per && (status == PackageManager.PERMISSION_GRANTED);
        }
        return per;
    }

    /**
     * check whether gps is open
     */
    public static void checkGPS(Activity act) {
        LocationManager manager = (LocationManager) act.getSystemService(Context.LOCATION_SERVICE);
        boolean isGPSEnabled = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (!isGPSEnabled) {
//            manager.s
            Toast.makeText(act, "请开启GPS", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            act.startActivity(intent);
        }
    }

    /**
     * request permission
     * requestCode use for handling recall msg
     */
    public static void requestPermission(Activity activity, String permission, int requestCode) {
        ActivityCompat.requestPermissions(activity, new String[]{permission}, requestCode);
    }

    public static void requestPermission(Activity activity, String[] permission, int requestCode) {
        ActivityCompat.requestPermissions(activity, permission, requestCode);
    }
}
